/* Copyright (C) 2015-2016 HangZhou Zenzet Technology Co., Ltd.
 * All right reserved

 * File:crypto/locketcommon.c
 * Author:guojianchuan/max
 * Date:2016-06-02
 
 */

/* system header */
#ifdef UNIX /* 重要:Linux下需要重定义为64, 才能操作>2GB以上的文件 */
#undef    _FILE_OFFSET_BITS   
#define   _FILE_OFFSET_BITS   64   
#endif
#include <stdlib.h>
#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>

/* 3rd project header */
#include "openssl/err.h"

/* my project header */
#include "locketcommon.h"


/**
* @Function:LOCKET_ERR_GetString 
* @Author: guojianchuan/max
* @Date: 2016-06-02
* @Description: Get error string
* caution: format error:140790E5:SSL routines:func(121):reason(229)
*/
char* LOCKET_ERR_GetString (void)
{
    int static iInit = 0;
    
    /* 加载错误信息 */
    if (!iInit)
    {
        ERR_load_ERR_strings();
        //ERR_load_crypto_strings(); 
        iInit = 1;
    }

    return ERR_error_string(ERR_get_error(),NULL);
}

/**
* @Function:LOCKET_malloc
* @Author: guojianchuan/max
* @Date: 2016-06-02
* @Description: malloc
* caution: 
*/
void* LOCKET_malloc (size_t size)
{
    return  (0 != size) ? malloc(size) : NULL;
}

/**
* @Function:LOCKET_free
* @Author: guojianchuan/max
* @Date: 2016-06-02
* @Description: free
* caution: 
*/
void LOCKET_free (void **p)
{
    if (NULL != *p)
    {
        free(*p);
        *p = NULL;
    }

    return;
}

/**
* @Function:LOCKET_GetFileSize
* @Author: guojianchuan/max
* @Date: 2016-08-08
* @Description: Get file size
* caution: 
*/
unsigned long long LOCKET_GetFileSize (char* pcPath)
{
    unsigned long long udlFileSize = INVALID_FILE_SIZE;

    if (NULL == pcPath)
    {
        return INVALID_FILE_SIZE;
    }

#ifdef WIN32
    struct _stat64 statbuf;
    if(_stat64(pcPath, &statbuf) < 0)
    {  
        return udlFileSize;  
    }
    else
    {  
        udlFileSize = statbuf.st_size;  
    }  
#elif UNIX
    struct stat statbuf;  
    if(stat(pcPath, &statbuf) < 0)
    {  
        return udlFileSize;  
    }
    else
    {  
        udlFileSize = statbuf.st_size;  
    }  
#elif APPLE
    struct stat statbuf;  
    if(stat(pcPath, &statbuf) < 0)
    {  
        return udlFileSize;  
    }
    else
    {  
        udlFileSize = statbuf.st_size;  
    }  
#endif

    return udlFileSize;
}

/* @Function:LOCKET_OpenFile
* @Author: guojianchuan/max
* @Date: 2016-08-08
* @Description: Open file
* caution: 
*/
FILE* LOCKET_OpenFile (char* pcPath, char* pcMode)
{
    return fopen(pcPath, pcMode);
}

/* @Function:LOCKET_ReadFile
* @Author: guojianchuan/max
* @Date: 2016-08-08
* @Description: Read file
* caution: 
*/
size_t LOCKET_ReadFile (void *ptr, size_t size, size_t nmemb, FILE *stream)
{
    return fread(ptr, size, nmemb, stream);
}

/* @Function:LOCKET_WriteFile
* @Author: guojianchuan/max
* @Date: 2016-08-08
* @Description: Write file
* caution: 
*/
size_t LOCKET_WriteFile (void *ptr, size_t size, size_t nmemb, FILE *stream)
{
    return fwrite(ptr, size, nmemb, stream);
}

